package com.dinadi.yidi.ui.activity;

import android.content.Intent;
import android.support.design.widget.AppBarLayout;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.dinadi.yidi.R;
import com.dinadi.yidi.adapter.MainPagerAdapter;
import com.dinadi.yidi.base.BaseActivity;
import com.dinadi.yidi.base.BaseFragment;
import com.dinadi.yidi.bean.CollectionBean;
import com.dinadi.yidi.bean.UserInformationBean;
import com.dinadi.yidi.http.AppBarStateChangeListener;
import com.dinadi.yidi.http.HttpListener;
import com.dinadi.yidi.http.interfaces.CommonInterface;
import com.dinadi.yidi.http.interfaces.IntegralChangeInterface;
import com.dinadi.yidi.ui.fragment.DesignerArticleFragment;
import com.dinadi.yidi.ui.fragment.DesignerCollectionFragment;
import com.dinadi.yidi.ui.fragment.DesignerFollowFragment;
import com.dinadi.yidi.ui.fragment.DesignerWorksFragment;
import com.dinadi.yidi.ui.view.ShareMenuPopupWindow;
import com.dinadi.yidi.utils.ImageUtils;
import com.dinadi.yidi.utils.JsonUtil;
import com.dinadi.yidi.utils.SharePreferencesHelper;
import com.dinadi.yidi.utils.ToastUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;

/**
 * author: JiaYu.He
 * Date: 2017/4/5   设计师的资料
 * Time: 15:21
 */

public class DesignerInformationActivity extends BaseActivity {

    private View view;
    private TextView tvTitle, nick_name, brand_name, signature, follow_num, tv_follow;
    private CircleImageView head_img;
    private Button btn_title_right;
    private ImageView follow;
    private RadioButton rb_works, rb_brand;
    private ViewPager id_activity_main_vp;
    private MainPagerAdapter mAdapter;
    private List<BaseFragment> fragments = new ArrayList<>();
    private List<RadioButton> radioButtons = new ArrayList<>();
    private String dUserId, userId, type, token, status;
    private String haveFlow, d_userId;
    /*判断是否登陆*/
    private boolean loginState;
    private int sharePosition;
    private ShareMenuPopupWindow selectImage;
    private LinearLayout layout_head;
    private AppBarLayout appBarLayout;
    private String htmlPath, nickName, headImg;

    @Override
    protected View getLayout() {
        view = LayoutInflater.from(DesignerInformationActivity.this).inflate(R.layout.activity_designer_homepage, null);
        return view;
    }

    @Override
    protected void noWifiRefresh() {

    }

    @Override
    protected void initView() {
        changePager(2);
        tvTitle = (TextView) view.findViewById(R.id.text_title);
        btn_title_right = (Button) view.findViewById(R.id.btn_title_right);
        btn_title_right.setBackgroundResource(R.drawable.product_details_icon_share);
        btn_title_right.setVisibility(View.GONE);
        head_img = (CircleImageView) view.findViewById(R.id.head_img);
        nick_name = (TextView) view.findViewById(R.id.nick_name);
        brand_name = (TextView) view.findViewById(R.id.brand_name);
        signature = (TextView) view.findViewById(R.id.signature);
        follow_num = (TextView) view.findViewById(R.id.follow_num);
        follow = (ImageView) view.findViewById(R.id.follow);
        rb_works = (RadioButton) view.findViewById(R.id.rb_works);
        rb_brand = (RadioButton) view.findViewById(R.id.rb_brand);
        id_activity_main_vp = (ViewPager) view.findViewById(R.id.id_activity_main_vp);
        tv_follow = (TextView) view.findViewById(R.id.tv_follow);
        layout_head = (LinearLayout) view.findViewById(R.id.layout_head);
        appBarLayout = (AppBarLayout) view.findViewById(R.id.appBarLayout);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void initListener() {
        registerClickListener(follow, btn_title_right);
        rb_works.setOnClickListener(this);
        rb_brand.setOnClickListener(this);
        id_activity_main_vp.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                selectRadioButton(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    @Override
    public void onResume() {
        super.onResume();
        String isRefresh = SharePreferencesHelper.getInstance(DesignerInformationActivity.this).getString("isRefresh");
        if ("yes".equals(isRefresh)) {
            userId = SharePreferencesHelper.getInstance(DesignerInformationActivity.this).getString("userId");
            token = SharePreferencesHelper.getInstance(DesignerInformationActivity.this).getString("token");
            loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");
            SharePreferencesHelper.getInstance(DesignerInformationActivity.this).putString("isRefresh", "no");
        }


    }

    @Override
    protected void initData() {
        loginState = SharePreferencesHelper.getInstance(this).getBoolean("loginState");
        token = SharePreferencesHelper.getInstance(this).getString("token");
        userId = SharePreferencesHelper.getInstance(this).getString("userId");

        Intent intent = getIntent();
        dUserId = intent.getStringExtra("dUserId");
        type = intent.getStringExtra("type");
        if (userId != null && userId.equals(dUserId)) {
            follow.setVisibility(View.GONE);
        }
        getHotspotDetails();

    }

    private void getHotspotDetails() {
        UserInformationBean bean = new UserInformationBean();
        bean.setUserId(dUserId);
        bean.setToken(token);
//        showLoadingDialog(getResources().getString(R.string.dialog_text));
        CommonInterface userInformationInetrface = new CommonInterface(DesignerInformationActivity.this, httpListener);
        userInformationInetrface.getInterface("11008", JSON.toJSONString(bean));
    }

    @Override
    protected void clickEvent(View v) {
        switch (v.getId()) {
            case R.id.follow:
                if (loginState == false) {
                    Intent loginIntent = new Intent();
                    loginIntent.setClass(this, LoginActivity.class);
                    startActivity(loginIntent);
                } else {
                    if (haveFlow.equals("0")) {
                        //否  进行关注
                        status = "1";
                        follow.setImageResource(R.drawable.icon_follow_selected_big);

                    } else if (haveFlow.equals("1")) {
                        //是  取消关注
                        status = "0";
                        follow.setImageResource(R.drawable.icon_follow_pressed_big);

                    }
                    CollectionBean bean = new CollectionBean();
                    bean.setToken(token);
                    bean.setStatus(status);
                    bean.setUserId(userId);
                    bean.setTargerUserId(d_userId);
                    CommonInterface userInformationInetrface = new CommonInterface(DesignerInformationActivity.this, collectionHttpListener);
                    userInformationInetrface.getInterface("11009", JSON.toJSONString(bean));
                }

                break;
            case R.id.rb_works:
                id_activity_main_vp.setCurrentItem(0);
                btn_title_right.setVisibility(View.GONE);
                break;
            case R.id.rb_brand:
                id_activity_main_vp.setCurrentItem(1);
                if (rb_brand.getText().equals("我的收藏")) {
                    btn_title_right.setVisibility(View.GONE);
                }else{
                    btn_title_right.setVisibility(View.VISIBLE);
                }

                break;
            case R.id.btn_title_right:
                /*分享*/
                ShowPickDialog();
                break;
            default:
                break;
        }

    }

    HttpListener httpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            String errMsg = JsonUtil.getFieldValue(response, "errMsg");
            if (errCode.equals("0000")) {
                closeLoadingDialog();
                nickName = JsonUtil.getFieldValue(response, "nickName");
                tvTitle.setText(nickName + "的主页");
                nick_name.setText(nickName);
                headImg = JsonUtil.getFieldValue(response, "headImg");
                //头像地址
                if (headImg.equals("null")) {
                    ImageUtils.loadImageView(DesignerInformationActivity.this, R.drawable.symbols_bitmap_head_portrait, head_img);

                } else {
                    if (!headImg.equals("")) {
                        ImageUtils.loadImageView(DesignerInformationActivity.this, headImg, head_img);
                    } else {
                        ImageUtils.loadImageView(DesignerInformationActivity.this, R.drawable.symbols_bitmap_head_portrait, head_img);
                    }
                }

                String brandName = JsonUtil.getFieldValue(response, "brandName");
                if (brandName.equals("null")) {
                    brand_name.setText("");

                } else {
                    brand_name.setText(brandName);
                }
                d_userId = JsonUtil.getFieldValue(response, "userId");
                haveFlow = JsonUtil.getFieldValue(response, "haveFlow");
                if (haveFlow.equals("0")) {
                    //否
                    follow.setImageResource(R.drawable.icon_follow_pressed_big);
                } else {
                    //是
                    follow.setImageResource(R.drawable.icon_follow_selected_big);
                }
                String signatures = JsonUtil.getFieldValue(response, "signature");
                if (signatures.equals("null")) {
                    signature.setText("");

                } else {
                    signature.setText(signatures);
                }
                String flowedNum = JsonUtil.getFieldValue(response, "flowedNum");
                follow_num.setText(flowedNum);
                SharePreferencesHelper.getInstance(DesignerInformationActivity.this).putString("brandName", brandName);
                String dUserId = JsonUtil.getFieldValue(response, "userId");
                SharePreferencesHelper.getInstance(DesignerInformationActivity.this).putString("dUserId", dUserId);
                /*文章*/
                htmlPath = JsonUtil.getFieldValue(response, "htmlPath");
                SharePreferencesHelper.getInstance(DesignerInformationActivity.this).putString("htmlPath", htmlPath);

                fragments.clear();
                // 添加tab名称和图标
                if (type.equals("1")) {
                    fragments.add(new DesignerFollowFragment());
                    fragments.add(new DesignerCollectionFragment());
                    radioButtons.add(rb_works);
                    radioButtons.add(rb_brand);
                    rb_works.setText("我的关注");
                    rb_brand.setText("我的收藏");
                    tv_follow.setText("粉丝");
                } else if (type.equals("2")) {
                    fragments.add(new DesignerWorksFragment());
                    fragments.add(new DesignerArticleFragment());
                    radioButtons.add(rb_works);
                    radioButtons.add(rb_brand);
                }
                selectRadioButton(0);
                id_activity_main_vp.setCurrentItem(0);

                if (mAdapter == null) {
                    mAdapter = new MainPagerAdapter(DesignerInformationActivity.this.getSupportFragmentManager(), fragments);
                    id_activity_main_vp.setAdapter(mAdapter);
                }

            } else {
                closeLoadingDialog();
                toast(errMsg);
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            closeLoadingDialog();
            toast("加载失败");
        }
    };

    /*关注*/
    HttpListener collectionHttpListener = new HttpListener() {
        @Override
        public void OnSuccess(String response) {
            super.OnSuccess(response);
            String errCode = JsonUtil.getFieldValue(response, "errCode");
            if (errCode.equals("0000")) {
                if (status.equals("1")) {
                    IntegralChangeInterface.IntegralChange(DesignerInformationActivity.this, userId, token, "9", "1", "关注成功");
                } else {
                    IntegralChangeInterface.IntegralChange(DesignerInformationActivity.this, userId, token, "9", "2", "取消关注");
                }
                getHotspotDetails();
            }
        }

        @Override
        public void OnFail(String errorResponse) {
            super.OnFail(errorResponse);
            toast("操作失败");
        }
    };

//    private float lastX = 0;
//    private float lastY = 0;
//
//    @Override
//    public boolean dispatchTouchEvent(MotionEvent event) {
//        super.dispatchTouchEvent(event);
//
//        final int action = event.getAction();
//
//        float x = event.getX();
//        float y = event.getY();
//
//        switch (action) {
//            case MotionEvent.ACTION_DOWN:
//                lastY = y;
//                lastX = x;
//                return false;
//            case MotionEvent.ACTION_MOVE:
//                float dY = Math.abs(y - lastY);
//                float dX = Math.abs(x - lastX);
//                boolean down = y > lastY;
//                lastY = y;
//                lastX = x;
//                if (dX < 8 && dY > 8 && !down) {
//                    layout_head.setVisibility(View.GONE);
//                } else if (dX < 8 && dY > 8 && down) {
//                    layout_head.setVisibility(View.VISIBLE);
//                } else {
//                    return false;
//                }
//                break;
//            default:
//                return false;
//        }
//        return false;
//    }


    /**
     * 设置当前选中的radiobutton的文字颜色
     *
     * @param i
     */
    private void selectRadioButton(int i) {
        for (int j = 0; j < 2; j++) {
            if (j == i) {
                radioButtons.get(j).setTextColor(getResources().getColor(R.color.sjs_text));
                radioButtons.get(j).setChecked(true);
            } else {
                radioButtons.get(j).setTextColor(getResources().getColor(R.color.home_text));
            }
        }
        if (i == 0) {
            btn_title_right.setVisibility(View.GONE);
        } else {
            if (rb_brand.getText().equals("我的收藏")) {
                btn_title_right.setVisibility(View.GONE);
            }else{
                btn_title_right.setVisibility(View.VISIBLE);
            }
        }

    }

    //弹出分享框
    private void ShowPickDialog() {
        if (selectImage == null) {
            selectImage = new ShareMenuPopupWindow(this);
            selectImage.setOnShareClickListener(shareClickListener);
        }
        selectImage.showAtLocation(this.findViewById(R.id.linearlayout_base), Gravity.BOTTOM, 0, 0);
    }

    private ShareMenuPopupWindow.OnShareClickListener shareClickListener = new ShareMenuPopupWindow.OnShareClickListener() {

        @Override
        public void onShareClick(int position) {
            screenshot(position);
        }
    };

    private void share() {
        ShareAction shareAction = new ShareAction(this);
        UMImage thumb = new UMImage(this, headImg);
        UMWeb web = new UMWeb("http://yididesign.cn/share_user_story.html?designerId=" + d_userId);
        web.setTitle(nickName+"的品牌故事");//标题
        web.setThumb(thumb);  //缩略图
        web.setDescription("来艺滴，看更多故事");//描述
        if (sharePosition == 1) {
            shareAction.setCallback(umShareListener).withMedia(web).share();


        } else {
            shareAction.setCallback(umShareListener).withMedia(web).share();

        }
        switch (sharePosition) {

            case 0:
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN); // 微信好友
                break;
            case 1:
                shareAction.setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE);// 微信朋友圈
                break;

        }
        shareAction.share();
    }

    public void screenshot(int position) {
//        if (!LoadDialog.isShowProgressDialog()) {
//            LoadDialog.showProgressDialog(getActivity(), "制作分享数据...", false, false);
        sharePosition = position;
        share();

        //   }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
            selectImage.dismiss();
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
            if (loginState == true) {
                IntegralChangeInterface.IntegralChange(DesignerInformationActivity.this, userId, token, "4", "1", "分享成功啦");
            } else {
                ToastUtil.showToast("分享成功啦");
            }
            selectImage.dismiss();
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(DesignerInformationActivity.this, " 分享失败啦", Toast.LENGTH_SHORT).show();
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
            selectImage.dismiss();
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(DesignerInformationActivity.this, " 分享取消了", Toast.LENGTH_SHORT).show();
            selectImage.dismiss();
        }

    };
}
